package com.dinglian.ots.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dinglian.ots.common.ToolUtils;
import com.dinglian.ots.common.model.Constant;
import com.dinglian.ots.dao.mapper.*;
import com.dinglian.ots.dao.model.*;
import com.dinglian.ots.exception.GlobalException;
import com.dinglian.ots.result.CodeMsg;
import com.dinglian.ots.service.OrderService;
import com.dinglian.ots.vo.cart.BrandCartVo;
import com.dinglian.ots.vo.order.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangbo
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderListMapper orderListMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private BrandRuleMapper brandRuleMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Value("${pic.path}")
    private String path;

    @Value("${pic.url}")
    private String url;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createElectionOrder(OrderVo orderVo) {
        List<ProductOrderVo> orderProductIdList = orderVo.getProductIdList();
        if (orderProductIdList.isEmpty()) {
            throw new GlobalException(CodeMsg.PRODUCT_ID_LIST_NULL);
        }

        List<Integer> productIdList = orderProductIdList.stream().map(ProductOrderVo::getProductId).collect(Collectors.toList());

        Integer userId = orderVo.getUserId();
        //查询当季 用户是否有选款单
//        Integer productId = productIdList.get(0);

        // 汇总各品牌商品
        Map<Integer, List<Integer>> brandProductMap = new HashMap<>();
        for (ProductOrderVo productOrderVo : orderProductIdList) {
            List<Integer> productIds = brandProductMap.get(productOrderVo.getBrandId());
            if (productIds == null) {
                productIds = new ArrayList<>();
            }
            productIds.add(productOrderVo.getProductId());
            brandProductMap.put(productOrderVo.getBrandId(), productIds);
        }

        //保存购物车Id，用于删除购物车
        List<Integer> cartIds = new ArrayList<>();
        List<Cart> allCarts = cartMapper.selectCartInfo(orderVo);
        // productId => Cart 每个商品的sku加入到不同订单
        Map<Integer, List<Cart>> productCartMap = new HashMap<>();
        for (Cart cart : allCarts) {
            List<Cart> carts = productCartMap.get(cart.getProductId());
            if (carts == null) {
                carts = new ArrayList<>();
            }
            carts.add(cart);
            productCartMap.put(cart.getProductId(), carts);
        }

        // 检查最小起订量是否达标
        // 查询各各商品最小起订量
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andIdIn(productIdList);
        List<Product> products = productMapper.selectByExample(productExample);

       /* // 统计各产品最小单色定量
        Map<Integer, Integer> productMinimumOrderMap = new HashMap<>();
        if (products != null) {
            for (Product product : products) {
                // 暂时只检查单色最小订量
                Integer colorMinimum = product.getColorMinimum();
                if (colorMinimum != null) {
                    productMinimumOrderMap.put(product.getId(), colorMinimum);
                }
            }
        }*/

        // 统计每个订单总量
        Map<Integer, Map> finalOrderMap = new HashMap<>();
        // 建立品牌 => 订单映射， 可能存在一个品牌对用多个季节订单
        Map<Integer, List<Integer>> brandOrdersMapping = new HashMap<>();

        // 各品牌分别生成订单
        for (Map.Entry<Integer, List<Integer>> entry : brandProductMap.entrySet()) {
            Integer brandId = entry.getKey();
            List<Integer> productIds = entry.getValue();

            Integer orderId = null;
            List<Cart> cartList = new ArrayList<>();

            for (Integer productId : productIds) {
                Product product = productMapper.selectByPrimaryKey(productId);
                // 获取当前产品相关购物车信息，当前订单只存当季商品信息
                cartList = productCartMap.get(productId);

                long totalAmt = 0;
                int totalQty = 0;

                // 获取当前品牌当季订单
                Order order = orderMapper.existElectionOrderSeason(userId, productId);
                if (order == null) {
                    order = new Order();
                    order.setType(Constant.ELECTION_ORDER);
                    order.setStatus(Constant.UNPAY);
                    order.setUserId(orderVo.getUserId());
                    order.setOrderno(ToolUtils.createOrderNo(""));
                    order.setQty(0);
                    order.setAmt(0L);
                    orderMapper.insertSelective(order);

                    orderId = order.getId();

                    for (Cart cart : cartList) {
                        Long amount = cart.getAmount();
                        Integer pId = cart.getProductId();
                        Integer quantity = cart.getQuantity();
                        Integer skuId = cart.getSkuId();
                        Integer id = cart.getId();

                        /*// 存在最小定量检查
                        if (productMinimumOrderMap.containsKey(pId.intValue())) {
                            if (quantity.intValue() < productMinimumOrderMap.get(pId.intValue())) {
                                throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_ORDER_QTY);
                            }
                        }*/

                        OrderList orderList = new OrderList();
                        orderList.setOrderId(orderId);
                        orderList.setSkuId(skuId);
                        orderList.setQty(quantity);
                        orderList.setProductId(pId);
                        orderList.setAmt(amount);

                        orderListMapper.insertSelective(orderList);

                        totalQty += quantity;
                        totalAmt += amount;

                        // 需要删除的购物车ID
                        cartIds.add(id);
                    }

                    // 更新订单总量
                    order.setAmt(totalAmt);
                    order.setQty(totalQty);
                    orderMapper.updateByPrimaryKeySelective(order);
                } else {
                    orderId = order.getId();
                    // 初始化
                    totalAmt = order.getAmt();
                    totalQty = order.getQty();

                    for (Cart cart : cartList) {
                        Long amount = cart.getAmount();
                        Integer pId = cart.getProductId();
                        Integer quantity = cart.getQuantity();
                        Integer skuId = cart.getSkuId();
                        Integer id = cart.getId();

                       /* // 存在最小定量检查
                        if (productMinimumOrderMap.containsKey(pId.intValue())) {
                            if (quantity.intValue() < productMinimumOrderMap.get(pId.intValue())) {
                                throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_ORDER_QTY);
                            }
                        }*/

                        OrderListExample orderListExample = new OrderListExample();
                        orderListExample.or().andOrderIdEqualTo(orderId).andSkuIdEqualTo(skuId);
                        List<OrderList> orderLists = orderListMapper.selectByExample(orderListExample);
                        if (orderLists.isEmpty()) {
                            OrderList orderList = new OrderList();
                            orderList.setOrderId(order.getId());
                            orderList.setSkuId(skuId);
                            orderList.setQty(quantity);
                            orderList.setProductId(pId);

                            BigDecimal amt = new BigDecimal(orderList.getQty()).multiply(new BigDecimal(product.getCostPrice()));
                            orderList.setAmt(amt.longValue());
                            orderListMapper.insertSelective(orderList);

                            totalAmt += amount;
                            totalQty += quantity;
                        } else {
                            OrderList orderList = orderLists.get(0);
                            orderList.setQty(orderList.getQty() + quantity);
//                            orderList.setAmt((new BigDecimal(qty).multiply(new BigDecimal(price)).longValue()));
//                            long amt = orderList.getQty() * product.getCostPrice();
                            BigDecimal amt = new BigDecimal(orderList.getQty()).multiply(new BigDecimal(product.getCostPrice()));
                            orderList.setAmt(amt.longValue());
                            orderListMapper.updateByPrimaryKeySelective(orderList);

                            totalAmt += orderList.getAmt();
                            totalQty += orderList.getQty();
                        }

//                        orderMapper.updateTotal(orderId);

                        // 需要删除的购物车ID
                        cartIds.add(id);
                    }

                    // 更新订单总量
                    order.setAmt(totalAmt);
                    order.setQty(totalQty);
                    orderMapper.updateByPrimaryKeySelective(order);
                }

                // 合并每个订单
                /*Map data = finalOrderMap.computeIfAbsent(order.getId(), v -> new HashMap());

                Long finalAmt = (Long) data.computeIfAbsent("finalAmt", v -> 0L);
                data.put("finalAmt", finalAmt + order.getAmt());

                Integer finalQty = (Integer) data.computeIfAbsent("finalQty", v -> 0);
                data.put("finalQty", finalQty + order.getQty());

                finalOrderMap.put(order.getId(), data);*/

                // 建立品牌订单映射
                List<Integer> orders = brandOrdersMapping.computeIfAbsent(brandId, v -> new ArrayList());
                if (!orders.contains(order.getId())) {
                    orders.add(order.getId());
                }
                brandOrdersMapping.put(brandId, orders);
                // end product each
            }

            //计算是否满足品牌起订量，此处为计算最小金额
            BrandWithBLOBs brandWithBLOBs = brandMapper.selectByPrimaryKey(brandId);
            String miniOrderQuantity = brandWithBLOBs.getMiniOrderQuantity();
            long miniOrderAmt = Long.parseLong(miniOrderQuantity);
            System.out.println("品牌起订量" + miniOrderAmt);

            // 查询当前品牌所有季节订单
            List<Integer> orders = brandOrdersMapping.get(brandId);
            for (Integer oid : orders) {
                Order order = orderMapper.selectByPrimaryKey(oid);
//                Map orderMap = finalOrderMap.get(oid);
//                Long finalAmt = (Long) orderMap.get("finalAmt");
//                Integer finalQty = (Integer) orderMap.get("finalQty");
                Long amt = order.getAmt();
                if (amt/100 < miniOrderAmt) {
                    System.out.println("不满足起订量");
                    throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_BRAND_QTY1.fillArgs(brandWithBLOBs.getName()));
                }

                //计算折后价格
                // TODO: 2020/4/8 此处可能存在BUG，没有区分季节，因为不同季节有不同订单，应该单独计算
                List<Map> brandList = orderListMapper.getBrandTotal(userId);
                for (int j = 0; j < brandList.size(); j++) {
                    Map map = brandList.get(j);
                    BigDecimal balance = calculateLadderPrice(map);
                    // TODO: 2020/4/8 当此处折后价为负数时，表示此单价格为0
                    if (balance.longValue() < 0) {
                        balance = new BigDecimal(0);
                    }
//                    Integer brandId = (Integer) map.get("brandId");
                    orderListMapper.updateBalance(orderId, brandId, balance.multiply(new BigDecimal(100)));
                }
            }

            // end brand each
        }

        //删除购物车信息
        CartExample cartExample = new CartExample();
        cartExample.or().andIdIn(cartIds);
        cartMapper.deleteByExample(cartExample);
    }


    /**
     * 计算折后价格
     */
    public BigDecimal calculateLadderPrice(Map map) {
        Integer brandId = (Integer) map.get("brandId");
        String totalAmount = ToolUtils.objectToString(map.get("totalAmt"));
        String totalQuantity = ToolUtils.objectToString(map.get("totalQty"));
        BigDecimal totalAmt = new BigDecimal(totalAmount);
        Integer totalQty = new BigDecimal(totalQuantity).intValue();


        //先判断是否含有金额规则或者数量规则
        BrandRuleExample amtbrandRuleExample = new BrandRuleExample();
        amtbrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(1);
        List<BrandRule> amtbrandRuleList = brandRuleMapper.selectByExample(amtbrandRuleExample);

        BrandRuleExample qtybrandRuleExample = new BrandRuleExample();
        qtybrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(2);
        List<BrandRule> qtyBrandRuleList = brandRuleMapper.selectByExample(qtybrandRuleExample);

        List<BigDecimal> balanceList = new ArrayList<>();

        if (!amtbrandRuleList.isEmpty()) {
            //金额
            List<Map> brandRules = brandRuleMapper.getAmtRuleByBrandId(brandId, totalAmt);
            if (brandRules.isEmpty()) {
               /* //满足最高条件
                List<Map> list = brandRuleMapper.satisfyAmtOrderCondition(brandId, totalAmt);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    String balance = ToolUtils.objectToString(brandRule.get("balance"));
                    BigDecimal bigDecimal = new BigDecimal(balance);
                    balanceList.add(bigDecimal);
                } else {
                    balanceList.add(new BigDecimal(totalAmt));
                }*/
            } else {
                Map brandRule = brandRules.get(0);
                Double balance = (Double) brandRule.get("balance");
                balanceList.add(new BigDecimal(balance));
            }
        }
        if (!qtyBrandRuleList.isEmpty()) {
            //数量
            List<Map> brandRules = brandRuleMapper.getQtyRuleByBrandId(brandId, totalQty, totalAmt);
            if (brandRules.isEmpty()) {
                /*//满足条件
                List<Map> list = brandRuleMapper.satisfyQtyOrderCondition(brandId, totalQty, totalAmt);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    String balance = ToolUtils.objectToString(brandRule.get("balance"));
                    BigDecimal bigDecimal = new BigDecimal(balance);
                    balanceList.add(bigDecimal);
                } else {
                    balanceList.add(new BigDecimal(totalAmt));
                }*/
            } else {
                Map brandRule = brandRules.get(0);
                Double balance = (Double) brandRule.get("balance");
                balanceList.add(new BigDecimal(balance));
            }
        }
        if (balanceList.isEmpty()) {
            balanceList.add(totalAmt);
        }
        BigDecimal min = Collections.min(balanceList);
        return min.setScale(2, BigDecimal.ROUND_HALF_UP);

    }


    @Override
    public PageInfo<OrderInfoVo> myElectionOrder(Integer userId, Integer seasonId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.getOrderBySeasonId(userId, seasonId);
        List<OrderInfoVo> orderInfoVos = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(orderInfoVos);
        if (orderList.isEmpty()) {
            return null;
        }
        for (int i = 0; i < orderList.size(); i++) {

            Order order = orderList.get(i);
            List<BrandOrderVo> brandOrderList = orderMapper.selectElectionOrderByBrand(userId, order.getId());
            OrderInfoVo orderInfoVo = new OrderInfoVo();
            orderInfoVo.setOrderId(order.getId());
            orderInfoVo.setOrderNo(order.getOrderno());
            orderInfoVo.setType(order.getType());
            Long orderAmt = order.getAmt();
            Double totalOrderAmt = new BigDecimal(orderAmt).divide(new BigDecimal(100)).setScale(2).doubleValue();
            orderInfoVo.setTotalAmt(totalOrderAmt);
            orderInfoVo.setStatus(order.getStatus());
            for (int j = 0; j < brandOrderList.size(); j++) {
                BrandOrderVo brandOrderVo = brandOrderList.get(j);
                Double totalAmount = brandOrderVo.getTotalAmount();
                Integer totalQuantity = brandOrderVo.getTotalQuantity();
                Integer brandId = brandOrderVo.getBrandId();
                BigDecimal balance = calculateLadderPrice1(brandId, new BigDecimal(totalAmount), totalQuantity);
                brandOrderVo.setTotalAmount(balance.doubleValue());

                //计算阶梯价格
                String content = calculateLadderPrice(brandId, new BigDecimal(totalAmount), totalQuantity);
                brandOrderVo.setContent(content);

            }
            orderInfoVo.setBrandOrderList(new PageInfo<>(brandOrderList));
            orderInfoVos.add(orderInfoVo);
        }

        return pageInfo;
    }


    @Override
    public void exportElectionOrder(Integer userId, Integer seasonId, Integer brandId, HttpServletResponse response) {

        BufferedImage bufferImg = null;
        SXSSFWorkbook wb = new SXSSFWorkbook();

        List<Map> list = orderMapper.exportElectionOrder(userId, seasonId, brandId);

        BigDecimal totalAmount = BigDecimal.ZERO;
        Integer totalQuantity  = 0;

        if (list.isEmpty()) {
            throw new GlobalException(CodeMsg.EXCEL_NO_DATA);
        }
        try {
            SXSSFSheet sheet = wb.createSheet("选款单");

            SXSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
            SXSSFRow rowCn = sheet.createRow(0);
            String brandName = null;
            for (int i = 0; i < Constant.PRODUCT_EXCEL_CN.length; i++) {
                SXSSFCell cell = rowCn.createCell(i);
                cell.setCellType(CellType.STRING);
                sheet.setColumnWidth(i, 5000);
                cell.setCellValue(Constant.PRODUCT_EXCEL_CN[i]);
            }
            SXSSFRow rowEn = sheet.createRow(1);
            for (int i = 0; i < Constant.PRODUCT_EXCEL_EN.length; i++) {
                SXSSFCell cell = rowEn.createCell(i);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(Constant.PRODUCT_EXCEL_EN[i]);
            }
            for (int i = 0; i < list.size(); i++) {
                Map map = list.get(i);
                SXSSFRow row = sheet.createRow(i + 2);
                row.setHeight((short) 2000);
                //图片
                String whitePic = ToolUtils.objectToString(map.get("whitePic"));
                if (!StrUtil.isBlank(whitePic)) {
                    whitePic = whitePic.replaceAll(url, path);
                    System.out.println("白底图的值" + whitePic);
                    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                    //将两张图片读到BufferedImage
                    File file = new File(whitePic);
                    if (file.exists()) {
                        System.out.println("文件存在");
                        bufferImg = ImageIO.read(file);
                        ImageIO.write(bufferImg, "png", byteArrayOut);
                        /**
                         * 该构造函数有8个参数
                         * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
                         * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
                         * excel中的cellNum和rowNum的index都是从0开始的
                         *
                         */
                        //图片一导出到单元格B2中
                        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, (short) 0, i + 2, (short) 1, i + 3);
                        // 插入图片
                        drawingPatriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                    }
                }

                //linesheet
                SXSSFCell cell = row.createCell(1);
                cell.setCellType(CellType.STRING);
                String name = ToolUtils.objectToString(map.get("productName"));
                cell.setCellValue(name);

                //订货季
                cell = row.createCell(2);
                cell.setCellType(CellType.STRING);
                String seasonName = ToolUtils.objectToString(map.get("seasonName"));
                cell.setCellValue(seasonName);

                //款式名称
                cell = row.createCell(3);
                cell.setCellType(CellType.STRING);
                String title = ToolUtils.objectToString(map.get("title"));
                cell.setCellValue(title);

                //款式编码
                cell = row.createCell(4);
                cell.setCellType(CellType.STRING);
                String styleName = ToolUtils.objectToString(map.get("stylename"));
                cell.setCellValue(styleName);

                //颜色
                cell = row.createCell(5);
                cell.setCellType(CellType.STRING);
                String colorName = ToolUtils.objectToString(map.get("colorName"));
                cell.setCellValue(colorName);

                //颜色号
                cell = row.createCell(7);
                cell.setCellType(CellType.STRING);
                String colorValue = ToolUtils.objectToString(map.get("colorValue"));
                cell.setCellValue(colorValue);

                //面料
                cell = row.createCell(8);
                cell.setCellType(CellType.STRING);
                String fabrication = ToolUtils.objectToString(map.get("fabrication"));
                cell.setCellValue(fabrication);

                //材质
                cell = row.createCell(10);
                cell.setCellType(CellType.STRING);
                String materials = ToolUtils.objectToString(map.get("materials"));
                cell.setCellValue(materials);

                //商品描述
                cell = row.createCell(11);
                cell.setCellType(CellType.STRING);
//                String description = ToolUtils.objectToString(map.get("description"));
                String description = "";
                cell.setCellValue(description);

                //分类
                cell = row.createCell(12);
                cell.setCellType(CellType.STRING);
                String categoryName = ToolUtils.objectToString(map.get("categoryName"));
                cell.setCellValue(categoryName);

                //二级分类
                cell = row.createCell(13);
                cell.setCellType(CellType.STRING);
                String subcategoryName = ToolUtils.objectToString(map.get("subcategoryName"));
                cell.setCellValue(subcategoryName);

                //尺码
                cell = row.createCell(14);
                cell.setCellType(CellType.STRING);
                String sizeName = ToolUtils.objectToString(map.get("sizeName"));
                cell.setCellValue(sizeName);

               /* //大货
                cell = row.createCell(15);
                cell.setCellType(CellType.STRING);
                String bulk = ToolUtils.objectToString(map.get("bulk"));
                cell.setCellValue(bulk);*/

                //OS
                cell = row.createCell(15);
                cell.setCellType(CellType.STRING);
                String OS = ToolUtils.objectToString(map.get("OS"));
                cell.setCellValue(OS);

                //XS
                cell = row.createCell(16);
                cell.setCellType(CellType.STRING);
                String XS = ToolUtils.objectToString(map.get("XS"));
                cell.setCellValue(XS);

                //S
                cell = row.createCell(17);
                cell.setCellType(CellType.STRING);
                String S = ToolUtils.objectToString(map.get("S"));
                cell.setCellValue(S);

                //M
                cell = row.createCell(18);
                cell.setCellType(CellType.STRING);
                String M = ToolUtils.objectToString(map.get("M"));
                cell.setCellValue(M);

                //L
                cell = row.createCell(19);
                cell.setCellType(CellType.STRING);
                String L = ToolUtils.objectToString(map.get("L"));
                cell.setCellValue(L);

                //XL
                cell = row.createCell(20);
                cell.setCellType(CellType.STRING);
                String XL = ToolUtils.objectToString(map.get("XL"));
                cell.setCellValue(XL);

                //XXL
                cell = row.createCell(21);
                cell.setCellType(CellType.STRING);
                String XXL = ToolUtils.objectToString(map.get("XXL"));
                cell.setCellValue(XXL);

                //35
                cell = row.createCell(22);
                cell.setCellType(CellType.STRING);
                String tf = ToolUtils.objectToString(map.get("tf"));
                cell.setCellValue(tf);

                //35½
                cell = row.createCell(23);
                cell.setCellType(CellType.STRING);
                String tfh = ToolUtils.objectToString(map.get("tfh"));
                cell.setCellValue(tfh);

                //36
                cell = row.createCell(24);
                cell.setCellType(CellType.STRING);
                String ts = ToolUtils.objectToString(map.get("ts"));
                cell.setCellValue(ts);

                //36½
                cell = row.createCell(25);
                cell.setCellType(CellType.STRING);
                String tsh = ToolUtils.objectToString(map.get("tsh"));
                cell.setCellValue(tsh);

                //37
                cell = row.createCell(26);
                cell.setCellType(CellType.STRING);
                String tse = ToolUtils.objectToString(map.get("tse"));
                cell.setCellValue(tse);

                //37½
                cell = row.createCell(27);
                cell.setCellType(CellType.STRING);
                String tseh = ToolUtils.objectToString(map.get("tseh"));
                cell.setCellValue(tseh);

                //38
                cell = row.createCell(28);
                cell.setCellType(CellType.STRING);
                String te = ToolUtils.objectToString(map.get("te"));
                cell.setCellValue(te);

                //38½
                cell = row.createCell(29);
                cell.setCellType(CellType.STRING);
                String teh = ToolUtils.objectToString(map.get("teh"));
                cell.setCellValue(teh);

                //39
                cell = row.createCell(30);
                cell.setCellType(CellType.STRING);
                String tn = ToolUtils.objectToString(map.get("tn"));
                cell.setCellValue(tn);

                //39½
                cell = row.createCell(31);
                cell.setCellType(CellType.STRING);
                String tnh = ToolUtils.objectToString(map.get("tnh"));
                cell.setCellValue(tnh);

                //40
                cell = row.createCell(32);
                cell.setCellType(CellType.STRING);
                String fty = ToolUtils.objectToString(map.get("fty"));
                cell.setCellValue(fty);

                //40½
                cell = row.createCell(33);
                cell.setCellType(CellType.STRING);
                String ftyh = ToolUtils.objectToString(map.get("ftyh"));
                cell.setCellValue(ftyh);

                //41
                cell = row.createCell(34);
                cell.setCellType(CellType.STRING);
                String fo = ToolUtils.objectToString(map.get("fo"));
                cell.setCellValue(fo);

                //41½
                cell = row.createCell(35);
                cell.setCellType(CellType.STRING);
                String foh = ToolUtils.objectToString(map.get("foh"));
                cell.setCellValue(foh);

                //42
                cell = row.createCell(36);
                cell.setCellType(CellType.STRING);
                String ft = ToolUtils.objectToString(map.get("ft"));
                cell.setCellValue(ft);

                //42½
                cell = row.createCell(37);
                cell.setCellType(CellType.STRING);
                String fth = ToolUtils.objectToString(map.get("fth"));
                cell.setCellValue(fth);

                //43
                cell = row.createCell(38);
                cell.setCellType(CellType.STRING);
                String ftt = ToolUtils.objectToString(map.get("ftt"));
                cell.setCellValue(ftt);

                //43½
                cell = row.createCell(39);
                cell.setCellType(CellType.STRING);
                String ftth = ToolUtils.objectToString(map.get("ftth"));
                cell.setCellValue(ftth);

                //44
                cell = row.createCell(40);
                cell.setCellType(CellType.STRING);
                String ff = ToolUtils.objectToString(map.get("ff"));
                cell.setCellValue(ff);

                //订货价
                cell = row.createCell(41);
                cell.setCellType(CellType.STRING);
                String costPrice = ToolUtils.objectToString(map.get("costPrice"));
                cell.setCellValue(costPrice);

                //建议零售价
                cell = row.createCell(42);
                cell.setCellType(CellType.STRING);
                String sellingPrice = ToolUtils.objectToString(map.get("sellingPrice"));
                cell.setCellValue(sellingPrice);

                BigDecimal costPriceBig = new BigDecimal(costPrice);
                BigDecimal sellingPriceBig = new BigDecimal(sellingPrice);

                //订货折扣  订货价/建议零售价*10 如45折
                cell = row.createCell(43);
                cell.setCellType(CellType.STRING);
                BigDecimal markDown = costPriceBig.divide(sellingPriceBig,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10)).setScale(2,BigDecimal.ROUND_HALF_UP);
//                String markDown = ToolUtils.objectToString(map.get("markDown"));
                cell.setCellValue(markDown.toString());

                //倍率  建议零售价/订货价
                cell = row.createCell(44);
                cell.setCellType(CellType.STRING);
                BigDecimal markUp = sellingPriceBig.divide(costPriceBig, 2, RoundingMode.HALF_UP);
//                String markUp = ToolUtils.objectToString(map.get("markUp"));
                cell.setCellValue(markUp.toString());

                //单位
                cell = row.createCell(46);
                cell.setCellType(CellType.STRING);
                String units = ToolUtils.objectToString(map.get("units"));
                cell.setCellValue(units);

                //单色最小订量
                cell = row.createCell(48);
                cell.setCellType(CellType.STRING);
                String totalQty = ToolUtils.objectToString(map.get("totalQty"));
                cell.setCellValue(totalQty);

                //最终单款价格
                cell = row.createCell(49);
                cell.setCellType(CellType.STRING);

//                String totalAmt = ToolUtils.objectToString(map.get("totalAmt"));




                //订货总额  满减之后的价格 最后一行展示
//                discountAmt = ToolUtils.objectToString(map.get("discountAmt"));

                //订货总额  订货价*订量
                cell = row.createCell(50);
                cell.setCellType(CellType.STRING);
//                String totalAmt = ToolUtils.objectToString(map.get("totalAmt"));
                BigDecimal totalAmt = new BigDecimal(costPrice).multiply(new BigDecimal(totalQty)).setScale(2, RoundingMode.HALF_UP);
                cell.setCellValue(totalAmt.toString());

                totalAmount = totalAmount.add(totalAmt);
                totalQuantity += Integer.valueOf(totalQty);
                //零售总额
                cell = row.createCell(51);
                cell.setCellType(CellType.STRING);
                String totalRetail = ToolUtils.objectToString(map.get("totalRetail"));
                cell.setCellValue(totalRetail);


//                BigDecimal discountAmtBig = new BigDecimal(discountAmt);

                //折扣  1-(订货价/零售价)
                cell = row.createCell(45);
                cell.setCellType(CellType.STRING);
                BigDecimal discount = (BigDecimal.ONE).subtract(costPriceBig.divide(sellingPriceBig,2,BigDecimal.ROUND_HALF_UP));
//                String discount = ToolUtils.objectToString(map.get("discount"));
//                cell.setCellValue(discount.toString());
//                BigDecimal discount = (BigDecimal.ONE).subtract(markDown);
                cell.setCellValue((discount.multiply(new BigDecimal(100))).toString());


                brandName = ToolUtils.objectToString(map.get("brandName"));
            }
            SXSSFRow row = sheet.createRow(list.size() + 3);
            SXSSFCell cell = row.createCell(50);
            cell.setCellType(CellType.STRING);
           BigDecimal discountAmt =  calculateLadderPrice1(brandId,totalAmount,totalQuantity);
            cell.setCellValue(discountAmt.toString());

            response.reset();
            //response为HttpServletResponse对象
            response.setContentType("application/octet-stream;charset=utf-8");


            String fileName = null;
            try {
                fileName = URLEncoder.encode(brandName + "选款单", "UTF-8");
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = null;
            out = response.getOutputStream();
            wb.write(out);
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ProductOrderVo> myElectionOrderInfo(Integer userId, Integer seasonId, Integer brandId, Integer pageNum, Integer pageSize) {
        List<Map> orderList = orderMapper.selectElectionOrderInfo(userId, seasonId, brandId);
        List<ProductOrderVo> productOrderVoList = new ArrayList<>();
        Map productMap = new HashMap();
        DecimalFormat df = new DecimalFormat("#.00");
        for (int i = 0; i < orderList.size(); i++) {
            Map orderMap = orderList.get(i);
            String productName = (String) orderMap.get("productName");
            Integer productId = (Integer) orderMap.get("productId");
            Integer orderId = (Integer) orderMap.get("orderId");
            String sizeName = (String) orderMap.get("sizeName");
            Integer skuId = (Integer) orderMap.get("skuId");
            String thumbnail = (String) orderMap.get("thumbnail");
            String stylename = (String) orderMap.get("stylename");
            Long colorMinimum = (Long) orderMap.get("colorMinimum");
            String title = (String) orderMap.get("title");
            String colorName = (String) orderMap.get("colorName");
            String cp = ToolUtils.objectToString(orderMap.get("costPrice"));
            BigDecimal costPrice = new BigDecimal(cp);
            String sp = ToolUtils.objectToString(orderMap.get("sellingPrice"));
            BigDecimal sellingPrice = new BigDecimal(sp);
            Integer qty = (Integer) orderMap.get("qty");
            String amt = ToolUtils.objectToString(orderMap.get("amt"));
            BigDecimal amount = new BigDecimal(amt);

            List<Map> sizeList = new ArrayList<>();
            Map sizeMap = new HashMap();

            ProductOrderVo productOrderVo = (ProductOrderVo) productMap.get(productId);
            if (productOrderVo == null) {
                productOrderVo = new ProductOrderVo();
                productOrderVo.setBrandId(brandId);
                double amount1 = amount.setScale(2, RoundingMode.HALF_UP).doubleValue();
                productOrderVo.setTotalAmt(df.format(amount1));
                productOrderVo.setThumbnail(thumbnail);
                double sellingPrice1 = sellingPrice.setScale(2, RoundingMode.HALF_UP).doubleValue();
                productOrderVo.setSellingPrice(df.format(sellingPrice1));
                productOrderVo.setProductId(productId);
                productOrderVo.setOrderId(orderId);
                productOrderVo.setName(productName);
                double costPrice1 = costPrice.setScale(2, RoundingMode.HALF_UP).doubleValue();
                productOrderVo.setCostPrice(df.format(costPrice1));
                productOrderVo.setTitle(title);
                productOrderVo.setColorName(colorName);
                productOrderVo.setStylename(stylename);
                productOrderVo.setColorMinimum(colorMinimum);
                sizeMap.put("skuId", skuId);
                sizeMap.put("sizeName", sizeName);
                sizeMap.put("qty", qty);
                sizeList.add(sizeMap);
                productOrderVo.setSizeList(sizeList);
                productMap.put(productId, productOrderVo);

                productOrderVoList.add(productOrderVo);
            } else {
                String totalAmt = productOrderVo.getTotalAmt();
                double totalAmt1 = (new BigDecimal(totalAmt).add(amount)).setScale(2, RoundingMode.HALF_UP).doubleValue();
                productOrderVo.setTotalAmt(df.format(totalAmt1));
                sizeList = productOrderVo.getSizeList();
                sizeMap.put("skuId", skuId);
                sizeMap.put("sizeName", sizeName);
                sizeMap.put("qty", qty);
                sizeList.add(sizeMap);
            }
        }
        return productOrderVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map updateMyElectionOrderInfo(UpdateElectionOrder updateElectionOrder) {
        Integer skuId = updateElectionOrder.getSkuId();
        Integer quantity = updateElectionOrder.getQuantity();
        Integer orderId = updateElectionOrder.getOrderId();

        Order order = orderMapper.selectByPrimaryKey(orderId);
        //判断是否小于起订量
        //整个品牌起订量


        Map skuMap = skuMapper.selectProductPrice(skuId);

        String costPriceStr = ToolUtils.objectToString(skuMap.get("costPrice"));
        Integer costPrice = 0;
        if (!StrUtil.isBlank(costPriceStr)) {
            costPrice = Integer.valueOf(costPriceStr);
        }
        Integer productId = (Integer) skuMap.get("id");
//        Integer costPrice = sku.getCostPrice();
        OrderListExample orderListExample = new OrderListExample();
        orderListExample.or().andSkuIdEqualTo(skuId).andOrderIdEqualTo(orderId);
        OrderList orderList = new OrderList();
        orderList.setQty(quantity);
        orderList.setAmt(Long.valueOf(quantity * costPrice));
        orderListMapper.updateByExampleSelective(orderList, orderListExample);

//        Integer productId = sku.getProductId();
        //获取产品最小订量和品牌最小订量
        Map miniMap = productMapper.getMiniQty(productId);
        Long colorMini = (Long) miniMap.get("colorMini");
        String miniQty = (String) miniMap.get("miniQty");
        if (!StringUtils.isNumeric(miniQty) && !StrUtil.isBlank(miniQty)) {
            throw new GlobalException(CodeMsg.BRAND_QTY);
        }
        //获取产品订量
        Integer qty = orderListMapper.getProductQty(productId, orderId);
        if (qty < colorMini) {
            throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_ORDER_QTY);
        }
        //获取品牌起订量
        Double brandQty = orderListMapper.getBrandQty(productId, orderId);
        BigDecimal brandAmt = new BigDecimal(brandQty);
        if (miniQty != null) {
            if (brandAmt.compareTo(new BigDecimal(miniQty)) == -1) {
                throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_BRAND_QTY);
            }
        }


        Map map = orderListMapper.getProductTotal(orderId, skuId);
//        Map map = orderListMapper.getBrandTotalBySkuId(orderId, skuId);
        Integer brandId = (Integer) map.get("id");
        BigDecimal totalAmount = (BigDecimal) map.get("amt");
        BigDecimal totalQuantity = (BigDecimal) map.get("qty");
        //计算阶梯价格
        String content = calculateLadderPrice(brandId, totalAmount, totalQuantity.intValue());
        Map productMap = new HashMap();
        productMap.put("content", content);
        productMap.put("amt", totalAmount.setScale(2));

        //计算折后价格
        Map brandList = orderListMapper.getBrandTotalByBrandId(order.getUserId(), brandId);
        BigDecimal balance = calculateLadderPrice(brandList);
        System.out.println("计算后的价格" + balance);
        orderListMapper.updateBalance(orderId, brandId, balance.multiply(new BigDecimal(100)));

        return productMap;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map deleteMyElectionOrderInfo(DeleteElectionOrder deleteElectionOrder) {
        Integer productId = deleteElectionOrder.getProductId();

        Integer orderId = deleteElectionOrder.getOrderId();
        Order order = orderMapper.selectByPrimaryKey(orderId);
        OrderListExample orderListExample = new OrderListExample();
        orderListExample.or().andProductIdEqualTo(productId).andOrderIdEqualTo(orderId);
        orderListMapper.deleteByExample(orderListExample);

        //获取产品最小订量和品牌最小订量
        Map miniMap = productMapper.getMiniQty(productId);
        String colorMiniStr = ToolUtils.objectToString(miniMap.get("colorMini"));
        String miniQtyStr = ToolUtils.objectToString(miniMap.get("miniQty"));
        Integer miniQty = 0;
        if (!StrUtil.isBlank(miniQtyStr)) {
            miniQty = Integer.valueOf(miniQtyStr);
        }

        /*//获取产品订量
        Integer qty = orderListMapper.getProductQty(productId, orderId);
        if (qty < colorMini) {
            throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_ORDER_QTY);
        }*/
        Map productMap = new HashMap();
        //获取品牌起订量
        Double brandQty = orderListMapper.getBrandQty(productId, orderId);
        if (brandQty == null) {
            throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_BRAND_QTY);
        } else {
            BigDecimal brandAmt = new BigDecimal(brandQty);
            if (miniQty != null) {
                if (brandAmt.compareTo(new BigDecimal(miniQty)) == -1) {
                    throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_BRAND_QTY);
                }
            }
        }

        /*int brandQty1 = 0;
        if (brandQty != null) {
            if (brandQty1 < Integer.valueOf(miniQty)) {
                throw new GlobalException(CodeMsg.LESS_THAN_MINIMUM_BRAND_QTY);
            }
            Map map = orderListMapper.getProductTotalByProductId(orderId, productId);
            Integer brandId = (Integer) map.get("id");
            BigDecimal totalAmount = (BigDecimal) map.get("amt");
            BigDecimal totalQuantity = (BigDecimal) map.get("qty");
        } else {
//            orderMapper.deleteByPrimaryKey(orderId);
        }*/

        return productMap;
    }

    /**
     * 计算阶梯价格
     *
     * @return
     */
    private String calculateLadderPrice(Integer brandId, BigDecimal totalAmount, Integer totalQuantity) {

        //先判断是否含有金额规则或者数量规则
        BrandRuleExample amtbrandRuleExample = new BrandRuleExample();
        amtbrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(1);
        List<BrandRule> amtbrandRuleList = brandRuleMapper.selectByExample(amtbrandRuleExample);

        BrandRuleExample qtybrandRuleExample = new BrandRuleExample();
        qtybrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(2);
        List<BrandRule> qtyBrandRuleList = brandRuleMapper.selectByExample(qtybrandRuleExample);
        String content = "";

        List<BigDecimal> discountList = new ArrayList<>();
        Map discountMap = new HashMap();

        if (!amtbrandRuleList.isEmpty()) {
            //金额
            List<Map> brandRules = brandRuleMapper.selectAmtRuleByBrandId(brandId, totalAmount);
            if (brandRules.isEmpty()) {
                //满足条件
                List<Map> list = brandRuleMapper.satisfyAmtCondition(brandId, totalAmount);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    //已减金额
                    String discount = ToolUtils.objectToString(brandRule.get("discount"));
                    BigDecimal bigDiscount = new BigDecimal(discount);
                    discountList.add(bigDiscount);
                    //满足金额
                    String standardAmount1 = ToolUtils.objectToString(brandRule.get("standardAmount"));
                    content = "金额已达到" + new BigDecimal(standardAmount1).doubleValue() + "元，已优惠" + new BigDecimal(discount).setScale(2, BigDecimal.ROUND_HALF_UP) + "元。";
                    discountMap.put(bigDiscount.toString(), content);
                }
            } else {
                Map brandRule = brandRules.get(0);
                //优惠金额
                String discount = ToolUtils.objectToString(brandRule.get("discount"));
                BigDecimal bigDiscount = new BigDecimal(discount);
                discountList.add(bigDiscount);
                //差值
                String difference = ToolUtils.objectToString(brandRule.get("difference"));
                content = "距下一级阶段还差" + new BigDecimal(difference).setScale(2, BigDecimal.ROUND_HALF_UP) + "元。";
                discountMap.put(discount.toString(), content);
            }
        }
        if (!qtyBrandRuleList.isEmpty()) {
            //数量
            List<Map> brandRules = brandRuleMapper.selectQtyRuleByBrandId(brandId, totalQuantity, totalAmount);
            if (brandRules.isEmpty()) {
                //满足条件
                List<Map> list = brandRuleMapper.satisfyQtyCondition(brandId, totalQuantity, totalAmount);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    //已减金额
                    String discount = ToolUtils.objectToString(brandRule.get("discount"));
                    //满足数量
                    String standardQty = ToolUtils.objectToString(brandRule.get("standardAmount"));
                    BigDecimal bigDiscount = new BigDecimal(discount);
                    discountList.add(bigDiscount);
                    content = "数量已达到" + new BigDecimal(standardQty).intValue() + "件，已优惠" + new BigDecimal(discount).setScale(2, BigDecimal.ROUND_HALF_UP) + "元。";
                    discountMap.put(bigDiscount.toString(), content);
                }

            } else {
                Map brandRule = brandRules.get(0);
                //优惠金额
                String discount = ToolUtils.objectToString(brandRule.get("discount"));
                //差值
                String difference = ToolUtils.objectToString(brandRule.get("difference"));
                BigDecimal bigDiscount = new BigDecimal(discount);
                discountList.add(bigDiscount);
                content = "距下一级阶段还差" + new BigDecimal(difference).setScale(2, BigDecimal.ROUND_HALF_UP) + "件。";
                discountMap.put(discount.toString(), content);
            }
        }

        if (discountList.isEmpty()) {
            content = "暂无优惠";
        } else {
            BigDecimal max = Collections.max(discountList);
            content = ToolUtils.objectToString(discountMap.get(max.toString()));
        }
        return content;
    }


    @Override
    public Map getOrderListRule(Integer userId, Integer brandId) {
        Map map = orderMapper.getBrandOrderTotal(userId, brandId);
        BigDecimal totalAmount = (BigDecimal) map.get("totalAmt");
//        totalAmount = totalAmount.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
        BigDecimal totalQuantity = (BigDecimal) map.get("totalQty");
        String miniQty = (String) map.get("miniQty");
        //计算阶梯价格
        String content = calculateLadderPrice(brandId, totalAmount, totalQuantity.intValue());
        Map productMap = new HashMap();
        productMap.put("content", content);
        productMap.put("totalQty", totalQuantity);
        productMap.put("miniQty", miniQty);
        BigDecimal balance = calculateLadderPrice1(brandId, totalAmount, totalQuantity.intValue());
        productMap.put("balance", balance);

        return productMap;
    }


    /**
     * 计算折后价格
     */
    public BigDecimal calculateLadderPrice1(Integer brandId, BigDecimal totalAmt, Integer totalQty) {


        //先判断是否含有金额规则或者数量规则
        BrandRuleExample amtbrandRuleExample = new BrandRuleExample();
        amtbrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(1);
        List<BrandRule> amtbrandRuleList = brandRuleMapper.selectByExample(amtbrandRuleExample);

        BrandRuleExample qtybrandRuleExample = new BrandRuleExample();
        qtybrandRuleExample.or().andBrandIdEqualTo(brandId).andOrderRuleEqualTo(2);
        List<BrandRule> qtyBrandRuleList = brandRuleMapper.selectByExample(qtybrandRuleExample);

        List<BigDecimal> balanceList = new ArrayList<>();

        if (!amtbrandRuleList.isEmpty()) {
            //金额
            List<Map> brandRules = brandRuleMapper.getAmtRuleByBrandId(brandId, totalAmt);
            if (brandRules.isEmpty()) {
               /* //满足最高条件
                List<Map> list = brandRuleMapper.satisfyAmtOrderCondition(brandId, totalAmt);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    String balance = ToolUtils.objectToString(brandRule.get("balance"));
                    BigDecimal bigDecimal = new BigDecimal(balance);
                    balanceList.add(bigDecimal);
                } else {
                    balanceList.add(new BigDecimal(totalAmt));
                }*/
            } else {
                Map brandRule = brandRules.get(0);
                Double balance = (Double) brandRule.get("balance");
                balanceList.add(new BigDecimal(balance));
            }
        }
        if (!qtyBrandRuleList.isEmpty()) {
            //数量
            List<Map> brandRules = brandRuleMapper.getQtyRuleByBrandId(brandId, totalQty, totalAmt);
            if (brandRules.isEmpty()) {
                /*//满足条件
                List<Map> list = brandRuleMapper.satisfyQtyOrderCondition(brandId, totalQty, totalAmt);
                if (!list.isEmpty()) {
                    Map brandRule = list.get(0);
                    String balance = ToolUtils.objectToString(brandRule.get("balance"));
                    BigDecimal bigDecimal = new BigDecimal(balance);
                    balanceList.add(bigDecimal);
                } else {
                    balanceList.add(new BigDecimal(totalAmt));
                }*/
            } else {
                Map brandRule = brandRules.get(0);
                Double balance = (Double) brandRule.get("balance");
                balanceList.add(new BigDecimal(balance));
            }
        }
        if (balanceList.isEmpty()) {
            balanceList.add(totalAmt);
        }
        BigDecimal min = Collections.min(balanceList);
        return min.setScale(2, BigDecimal.ROUND_HALF_UP);

    }



    @Override
    public Map getBrandOrderListRule(Integer userId, Integer brandId) {

        Map map = orderMapper.getBuyerOrderTotal(userId, brandId);
        BigDecimal totalAmount = (BigDecimal) map.get("totalAmt");
        totalAmount = totalAmount.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
        BigDecimal totalQuantity = (BigDecimal) map.get("totalQty");
        //计算阶梯价格
        String content = calculateLadderPrice(brandId, totalAmount, totalQuantity.intValue());
        Map productMap = new HashMap();
        productMap.put("content", content);
        productMap.put("totalQty", totalQuantity);
        productMap.put("miniQty", 0);
        BigDecimal balance = calculateLadderPrice1(brandId, totalAmount, totalQuantity.intValue());
        productMap.put("balance", balance);

        return productMap;
    }


}
